""""
    通过cvzone进行手势识别，根据用户的手势开启不同的输入模式，完成对应的自动化操作
"""
import cv2
from cvzone.HandTrackingModule import HandDetector
from threading import Thread, Lock


cap = cv2.VideoCapture(0)
detector = HandDetector(detectionCon=0.8)
# 模式开关，默认是开启的

mode_switch = True

gesture_cache = []
def select_mode(cache, switch):
    filter_hand = max(cache, key=cache.count)
    if filter_hand == [1, 1, 0, 0, 0] and switch is True:
        # 关闭模式开关
        print("选择了一")
        # 退出，将手势选择关闭
    if filter_hand == [1, 1, 1, 0, 0] and switch is True:
        print("选择了二")
        # 退出，将手势选择关闭
    if filter_hand == [1, 1, 1, 1, 0] and switch is True:
        print("选择了三")
        # 退出，将手势选择关闭
    if filter_hand == [1, 1, 1, 1, 1] and switch is True:
        print("选择了四")
        # 退出，将手势选择关闭
    if filter_hand == [1, 0, 0, 0, 0] and switch is True:
        # 关闭模式开关
        # 退出，将手势选择关闭
        print("选择了五")
    if filter_hand == [0, 1, 0, 0, 0] and switch is True:
        # 关闭模式开关
        print("选择了六")
    if filter_hand == [0, 1, 1, 0, 0] and switch is True:
        # 关闭模式开关
        print("选择了七")
    if filter_hand == [0, 1, 1, 1, 0] and switch is True:
        # 关闭模式开关
        print("选择了八")
    if filter_hand == [0, 1, 1, 1, 1] and switch is True:
        # 关闭模式开关
        print("选择了九")
    if filter_hand == [0, 0, 1, 1, 1] and switch is False:
        # 开启手势检测开关
        print("用户退出模式")
        return True
    return False





while True:
    success, img = cap.read()
    img = cv2.flip(img, 1)
    # imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    # 找到图片中的手
    hands, img = detector.findHands(img, flipType=False)
    # 找到了手
    if hands:
        for hand in hands:
            # 得到手关键点位置
            hand_list = detector.fingersUp(hand)
            # print(hand_list)
            # 将手部关键点存储进手部缓存中
            gesture_cache.append(hand_list)
            # 判断缓存中是否有足够的数据
            if len(gesture_cache) > 30:
                mode_switch = select_mode(gesture_cache, mode_switch)
                # print(mode_switch)
                gesture_cache = []

            # print(hand_list)
    cv2.imshow('video', img)
    cv2.waitKey(1)

